<script setup>
import { ref } from 'vue';
import { useFormOperate } from '@/hooks/pages-repeat';
import { createApi, updataApi, getInfoApi } from '@/api/sys/role';
import { listApi } from '@/api/sys/dept';
import { menuSelectApi } from '@/api/sys/menu';

const emits = defineEmits(['modalClose'])
const { 
  dataFormRef,
  modalOpen,
  confirmLoading,
  detailLoading,
  dataForm,
  requestObj,
  submit,
} = useFormOperate()

requestObj.value = {
  createApi,
  updataApi,
  submitCallback: emits
}
dataForm.value = {
  id: undefined,
  name: '',
  remark: '',
  menuIdList: [],
  deptIdList: [],
}
const rules = ref({
  name: [{ required: true, message: '请输入名称!' }],
})
const init = (id) => {
  modalOpen.value = true
  dataForm.value.id = id
  if (id) {
    getInfo()
  } else {
    getMenuSelectList()
    getDeptList()
  }
}
const getInfo = () => {
  detailLoading.value = true
  getInfoApi(dataForm.value.id).then(({data:res}) => {
    // 不给后端带过去多余的字段，想要的话再dataForm里面添加
    for (let key in dataForm.value) {
      dataForm.value[key] = res.data[key] || dataForm.value[key]
    }
    getMenuSelectList()
    getDeptList()
  }).finally(() => {
    detailLoading.value = false
  })
}

const menuIds = ref([])
const menuFatherIds = ref([])
const menuTreeChange = (keys, e) => {
  menuFatherIds.value = e.halfCheckedKeys
}
const menuList = ref([])
const getMenuSelectList = () => {
  menuSelectApi().then(({data:res}) => {
    menuList.value = res.data
    const fn = (list) => {
      list.forEach(item => {
        if (item.children.length) {
          let isFlage = dataForm.value.menuIdList.indexOf(item.id)
          if (isFlage !== -1) {
            menuFatherIds.value.push(item.id)
          }
          fn(item.children)
        } else {
          let isFlage = dataForm.value.menuIdList.indexOf(item.id)
          if (isFlage !== -1) {
            menuIds.value.push(item.id)
          }
        }
      })
    }
    fn(res.data)
  })
}

const deptIds = ref([])
const deptFatherIds = ref([])
const deptTreeChange = (keys, e) => {
  deptFatherIds.value = e.halfCheckedKeys
}
const deptList = ref([])
const getDeptList = () => {
  listApi().then(({data:res}) => {
    deptList.value = res.data
    const fn = (list) => {
      list.forEach(item => {
        if (item.children.length) {
          let isFlage = dataForm.value.deptIdList.indexOf(item.id)
          if (isFlage !== -1) {
            menuFatherIds.value.push(item.id)
          }
          fn(item.children)
        } else {
          let isFlage = dataForm.value.deptIdList.indexOf(item.id)
          if (isFlage !== -1) {
            deptIds.value.push(item.id)
          }
        }
      })
    }
    fn(res.data)
  })
}

const submits = () => {
  dataForm.value.menuIdList = [...new Set([...menuIds.value, ...menuFatherIds.value])]
  dataForm.value.deptIdList = [...new Set([...deptIds.value, ...deptFatherIds.value])]
  submit()
}
defineExpose({
  init
})

</script>

<template>
  <a-modal 
    width="60%"
    v-model:open="modalOpen" 
    :confirm-loading="confirmLoading"
    :title="dataForm.id ? '修改角色' : '新增角色'" 
    okText="确定"
    cancelText="取消"
    :bodyStyle="{'padding': '20px'}"
    @cancel="emits('modalClose')"
    :maskClosable="false"
    @ok="submits"
    >
    <a-spin :spinning="detailLoading">
      <a-form ref="dataFormRef" layout="vertical" :model="dataForm" :rules="rules" name="dataForm" autocomplete="off">
        <a-form-item label="名称" name="name">
          <a-input v-model:value.trim.trim="dataForm.name" placeholder="请输入角色名称" />
        </a-form-item>

        <a-form-item label="备注">
          <a-input v-model:value.trim.trim="dataForm.remark" placeholder="请输入备注" />
        </a-form-item>

        <a-row :gutter="10">
          <a-col :span="12">
            <a-form-item label="菜单授权">
              <a-tree
                v-if="menuList.length"
                :height="400"
                v-model:checkedKeys="menuIds"
                checkable
                :multiple="true"
                :tree-data="menuList"
                :fieldNames="{
                  title: 'name',
                  key: 'id'
                }"
                @check="menuTreeChange"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item label="数据授权">
              <a-tree
                v-if="deptList.length"
                :hieght="400"
                v-model:checkedKeys="deptIds"
                checkable
                :height="400"
                :tree-data="deptList"
                :fieldNames="{
                  title: 'name',
                  key: 'id'
                }"
                @check="deptTreeChange"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<style lang="scss" scoped>

</style>